<!-- 确认费用 -->
<template>
  <a-modal width="65vw" v-model:visible="visible" :mask-closable="false" :esc-to-close="false" unmount-on-close @close="onCancel">
    <template v-if="query?.title" #title> {{ query?.title }} </template>
    <div class="confirm-cost-box">
      <div class="fee-list">
        <div v-for="(item, index) in feeList" :key="index" style="margin: 0 20px">
          <ComfirmFeeItem :fee="item" />
        </div>
        <div class="all-cost">
          <span>合计</span>
          <div class="cost-num">
            <div>{{ costType == 0 ? '应收' : '应付' }}：{{ unitVal(Math.abs(feeCostAmount.receiveAmount), '元') }}</div>
            <div style="margin-top: 16px">
              {{ costType == 0 ? '待收' : '待付' }}：{{ unitVal(Math.abs(feeCostAmount.receivedNotAmount), '元') }}
            </div>
          </div>
        </div>
      </div>
      <a-divider />
      <page-form :model="form" layout="vertical" ref="formRef" style="overflow: hidden">
        <page-form-row>
          <page-form-item
            field="paymentTime"
            :label="costName + '时间'"
            :rules="[{ required: true, message: '请选择' + costName + '时间', trigger: 'change' }]"
          >
            <i-date-picker
              popup-container=".confirm-cost-box"
              class="w-full"
              v-model="form.paymentTime"
              show-time
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </page-form-item>

          <page-form-item
            field="paymentWay"
            :label="costName + '方式'"
            :rules="{ required: true, message: '请选择' + costName + '方式' }"
            labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              placeholder="请选择"
              v-model="form.paymentWay"
              @change="typeChange"
              :disabled="disabledCostType"
              popup-container=".confirm-cost-box"
            >
              <a-option v-for="item in paywayEnum" :key="item.way" :value="item.way" :label="item.wayStr" />
            </a-select>
          </page-form-item>

          <page-form-item
            field="account"
            :label="costName + '账号'"
            labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              :placeholder="!form.paymentWay ? '请先选择' + costName + '方式' : '请选择'"
              v-model="form.account"
              :disabled="!form.paymentWay ? true : false"
              popup-container=".confirm-cost-box"
            >
              <a-option v-for="item in accountList" :key="item.id" :value="item.id" :label="item.account" />
            </a-select>
          </page-form-item>

          <page-form-item
            field="actualAmount"
            :label="costName + '金额'"
            :rules="{ required: true, message: '请输入' + costName + '金额' }"
          >
            <i-input-number v-model="form.actualAmount" unit="元" :precision="2" disabled />
          </page-form-item>

          <page-form-item field="customerId" label="客户名称" :rules="{ required: true, message: '请输入客户名称' }">
            <a-select placeholder="请选择" v-model="form.customerId" popup-container=".confirm-cost-box" @change="onCustomerChange">
              <a-option v-for="(item, index) in supplierLists" :key="index" :value="item.id"> {{ item.supplierName }}</a-option>
            </a-select>
          </page-form-item>

          <page-form-item field="customerAccount" :label="costName == '收款' ? '客户付款账号' : '客户收款账号'">
            <i-input placeholder="请输入" v-model="form.customerAccount" :max-length="20" />
          </page-form-item>

          <page-form-item field="settlementRemark" label="结算备注" size="2/3">
            <i-input placeholder="请输入" v-model="form.settlementRemark" :max-length="200" />
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onCancel">关闭</a-button>
        <a-button type="primary" :loading="loading" @click="submitFn">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import ComfirmFeeItem from './components/comfirm-fee-item.vue'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/order/sOrder'
  import { confirmFeeInstallment, confirmFee, searchForStaff } from '@/api/asset/car'
  import { getSupplierList } from '@/api/asset/maintenance'
  import { getPeer } from '@/api/market/peer'
  import { unitVal } from '@/utils'
  import { Message } from '@arco-design/web-vue'

  const visible = ref(false)
  const loading = ref(false)
  const costType = ref(null) // type  0-收款，1-付款，3-收款&付款  (合计 正-收款  负-付款)
  const paywayEnum = ref<any>([]) //收付款方式
  const accountList = ref<any>([]) //收付款账号列表
  const costName = ref('')
  const feeList = ref<any>([]) // 收付款列表
  const feeCostAmount = ref<any>({}) //收付款类型及金额
  const formRef = ref()
  const disabledCostType = ref(false)
  const form = ref<any>({
    idList: [], //结算单ids
    carId: '',
  })

  const emits = defineEmits(['confirm'])

  // 获取购置费信息
  const feeConfirm = (ids: any) => {
    confirmFeeInstallment({ idList: ids }).then((res: any) => {
      feeCostAmount.value = res.result
      feeList.value = res.result.carAssetFeeList
      console.log(feeList.value, 'feeList')

      form.value.actualAmount = Math.abs(res.result.receiveAmount) //固定金额，不可修改
      costType.value = res.result.costType
      form.value.paymentTime = feeList.value[feeList.value.length - 1].createTime
      form.value.customerId = feeList.value[feeList.value.length - 1].supplierId
      form.value.customerAccount = res.result.receiveAccount
      if (costType.value == 0) {
        costName.value = '收款'
      } else {
        costName.value = '付款'
      }
      // 押金抵扣为固定收付款方式
      if (feeCostAmount.value.payType != null) {
        disabledCostType.value = true
        form.value.paymentWay = feeCostAmount.value.payType.toString()
      }
      getType()
    })
  }
  // 收付款类型
  const getType = () => {
    getAccountByPageData({ type: costType.value == 0 ? 0 : 1 }).then((res: any) => {
      res.result = res.result.filter(
        (item: any) =>
          item.way !== '0' &&
          item.way !== '1' &&
          item.way !== '2' &&
          item.way !== '3' &&
          item.way !== '4' &&
          item.way !== '5' &&
          item.way !== '-1'
      )
      paywayEnum.value = res.result
    })
  }
  // 账号
  const typeChange = (e: any) => {
    if (e) {
      form.value.account = ''
    }
    paywayEnum.value.forEach((el: any) => {
      if (el.way == e) {
        getAccountByWayAndType({ way: Number(el.way), type: Number(el.type) }).then((res: any) => {
          accountList.value = res.result
        })
      }
    })
  }

  const supplierLists = ref<any>([])
  const supplierList = () => {
    if (query.value.supplierType === 0) {
      getPeer({}).then((res: any) => {
        res.result.forEach((item: any) => {
          item.supplierName = item.industryName
          item.supplierId = item.industryId
        })
        supplierLists.value = res.result
      })
    } else if (query.value.supplierType === 1) {
      getSupplierList({ supplierType: 3, status: 1 }).then((res: any) => {
        supplierLists.value = res.result
        console.log(supplierLists.value, 'supplierLists')
      })
    } else {
      searchForStaff({ siteStatusList: [10], siteType: 40 }).then((res: any) => {
        res.result.forEach((item: any) => {
          item.supplierName = item.siteName
        })
        supplierLists.value = res.result
      })
    }
  }

  const onCustomerChange = (value: any) => {
    console.log(value, 'value')
    form.value.customerName = supplierLists.value.find((item: any) => item.id === value).supplierName
  }

  const onCancel = () => {
    visible.value = false
    formRef.value.resetFields()
    loading.value = false
  }

  const submitFn = () => {
    formRef.value.validate((error: any) => {
      if (!error) {
        loading.value = true
        const param = {
          ...form.value,
        }
        confirmFee(param)
          .then(() => {
            Message.success('操作成功')
            loading.value = false
            visible.value = false
            formRef.value.resetFields()
            emits('confirm')
          })
          .catch(() => {
            loading.value = false
          })
      }
    })
  }

  const query = ref()
  const open = (options: any) => {
    console.log(options, 'options')

    visible.value = true
    query.value = options
    form.value.idList = options.idList
    form.value.carId = options.carId
    form.value.customerType = options.supplierType
    form.value.customerName = options.supplierName
    feeConfirm(options.idList)
    supplierList()
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  .confirm-cost-box {
    width: 100%;
    max-height: 70vh;
    position: relative;
  }
  .fee-list {
    padding-top: 20px;
    border: 1px solid #f2f3f5;
  }
  .all-cost {
    font-weight: 600;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #f2f3f5;
    height: 100px;
    .cost-num {
      color: #1890ff;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
    }
  }
</style>
